// ==UserScript==
// @name       WME Street to Walking Trail
// @namespace  http://s2wr.googlecode.com/svn/trunk
// @version    0.0.1
// @description  To create RailRoad it transforms selected segments of type Street or Walking Rail with no city and street name equal to 'Ferrovia' in type Walking Trail with level -5, two ways, locked.
// @updateURL   https://s2wr.googlecode.com/svn/trunk/WME-Street-to-Walking-Trail.user.js
// @copyright  2013+, Zannax
// @include    https://*.waze.com/editor/*
// @include    https://*.waze.com/map-editor/*
// @include    https://*.waze.com/beta_editor/*
// ==/UserScript==

function bootstrapS2WR() {
  var bGreasemonkeyServiceDefined = false;
  
  try {
    bGreasemonkeyServiceDefined = (typeof Components.interfaces.gmIGreasemonkeyService === "object");
  }
  catch (err) { /* Ignore */ }
  
  if (typeof unsafeWindow === "undefined" || ! bGreasemonkeyServiceDefined) {
    unsafeWindow    = ( function () {
      var dummyElem = document.createElement('p');
      dummyElem.setAttribute('onclick', 'return window;');
      return dummyElem.onclick();
    }) ();
  }
  
  /* begin running the code! */
  setTimeout(initS2WR, 500);
}

function s2wrGlobals() {
  version = '0.0.1';
  s2wrLang = navigator.language || navigator.userLanguage;
  roadTypes = { "street": 1, "primary": 2, "freeway": 3, "ramp": 4,
               "trail": 5, "major": 6,  "minor": 7, "dirt": 8,
               "boardwalk": 10, "stairway": 16, "private": 17, "railroad": 18,
               "runway": 19, "parking": 20, "service": 21};
  typenames = { 1: "street", 2: "primary", 3: "freeway", 4: "ramp",
               5: "trail", 6: "major", 7: "minor", 8: "dirt",
               10: "boardwalk", 16: "stairway", 17: "private", 18: "railroad",
               19: "runway", 20: "parking", 21: "service"};
  s2wrMessages = {
    "it" : { "_NoLogged": "Nessun utente loggato",
            "_NoSelected": "Nessun segmento selezionato",
            "_MustBeSegment": "Gli elementi selezionati devono essere tutti segmenti",
            "_TypeStreetError": "I segmenti selezionati devono essere Street o Walking Trail",
            "_NameStreetError": "Il Nome Street deve essere: Ferrovia",
            "_NameCityError": "Il Nome City deve avere il flag None",
            "_UndefinedError": "Ci sono segmenti senza impostazioni City e Street"
           },
    "en" : { "_NoLogged": "No logged user",
            "_NoSelected": "No Selected segment",
            "_MustBeSegment": "Selected items must be segments only",
            "_TypeStreetError": "Selected segments must be Street or Walking Trail type",
            "_NameStreetError": "Street name must be: RailRoad",
            "_NameCityError": "City name must have None flag",
            "_UndefinedError": "There are segments without City and Street settings"
           }
  }
}

function s2wrWazeBits() {
  wazeMap = unsafeWindow.wazeMap;
  wazeModel = unsafeWindow.wazeModel;
  loginManager= unsafeWindow.loginManager;
  selectionManager= unsafeWindow.selectionManager;
  jq = unsafeWindow.jQuery;
  Waze = unsafeWindow.Waze;
  //Object = unsafeWindow.Object;
}

function s2wrInsertButton() {
  if(selectionManager.selectedItems.length == 0) return;
  if(document.getElementById('creaFerrovia') != null) return;
  
  var cnt = jq('<section id="creaFerrovia"/>');
  var btn1 = jq('<button id="S2WR" class="btn" title="Trasforma strada in ferrovia secondo la guida"> Crea Ferrovia </button>');
  btn1.click(s2wrCreateRail);
  cnt.append(btn1);
  
  jq("#segment-edit-general").append(cnt);
  
  //console.log("S2WR: initialised v. %s", version);
}

function getUsername() {
  var thisUser = loginManager.user;
  if (thisUser === null || thisUser.expired) {
    s2wrMsg('_NoLogged');
    return "";
  }
  
  return loginManager.user.userName;
}

//User Rank di un oggetto
function getUserRank(segment) {
  var usrRank = 0;
  if (segment.attributes.locked) {
    var updatedBy = wazeModel.users.get(segment.attributes.updatedBy);
    return updatedBy != null ? updatedBy.rank : 0;
  }
  
  return 0;
}

//Restituisce il livello di blocco massimo
function getLevel() {
  //attributes.rank dovrebbe essere il road rank
  var sel = selectionManager.selectedItems;
  var max = getUserRank(sel[0]);
  for (i = 1; i < sel.length; i++) {
    if (max == 5)
      return 5;
    
    var usrRank = getUserRank(sel[i]);
    if (usrRank > max) {
      max = usrRank;
    }
  }
  return max + 1;
}

function s2wrCreateRail() {
  if (selectionManager.selectedItems.length == 0) {
    s2wrMsg('_NoSelected');
    return;
  }
  
  var username = getUsername();
  var lockLevel = getLevel();
  var bOK = true;
  var nodes = {};
  var selsegments = selectionManager.selectedItems;
  var seg = null;
  
  for (var i = 0; i < selsegments.length; i++) {
    seg = selsegments[i];
    //console.log("segment: %o", seg);
    
    if (seg.type != Waze.Model.ObjectType.SEGMENT) {
      s2wrMsg("_MustBeSegment");
      bOK = false;
    }
    
    if (seg.attributes.roadType != roadTypes['trail'] && seg.attributes.roadType != roadTypes['street']) {
      s2wrMsg("_TypeStreetError");
      bOK = false;
    }
    
    if (seg.attributes.primaryStreetID) {
      var street = wazeModel.streets.get(seg.attributes.primaryStreetID);
      //console.log("street: %o", street);
      if (street.isEmpty || street.name != "Ferrovia") {
        s2wrMsg("_NameStreetError");
        bOK = false;
      }
      
      var city = wazeModel.cities.get(street.cityID);
      //console.log("city: %o", city);
      if (!city.isEmpty) {
        s2wrMsg("_NameCityError");
        bOK = false;
      }
      
      /*if (city) {
      if (!cities[street.cityID])
      cities[street.cityID] = 0;
      if (!city.isEmpty)
      cities[street.cityID] += 100;
      }*/
    } else {
      s2wrMsg("_UndefinedError");
      bOK = false;
    }
    
    if (!bOK) {
      break;
    } else {
      nodes[seg.attributes.toNodeID] = wazeModel.nodes.get(seg.attributes.toNodeID);
      nodes[seg.attributes.fromNodeID] = wazeModel.nodes.get(seg.attributes.fromNodeID);
    }
  }
  
  /* Sistemo i dati sui segmenti */
  for (var i = 0; i < selsegments.length && bOK; i++) {
    var newAttrs = {};
    var segAttrs = selsegments[i].attributes;
    var logmsg = "Segment ID: " + selsegments[i].fid + "\n";
    
    if (segAttrs.roadType != roadTypes['trail']) {
      newAttrs["roadType"] = roadTypes['trail'];
      logmsg += "roadType: " + segAttrs.roadType + " => " + roadTypes['trail'] + "\n";
    }
    
    if (segAttrs.level != -5) {
      newAttrs["level"] = -5;
      logmsg += "level: " + segAttrs.level + " => -5" + "\n";
    }
    
    if (segAttrs.locked != true) {
      newAttrs["locked"] = true;
      logmsg += "locked: " + segAttrs.locked + " => true" + "\n";
    }
    
    if (segAttrs.fwdDirection != true) {
      newAttrs["fwdDirection"] = true;
      logmsg += "fwdDirection: " + segAttrs.fwdDirection + " => true" + "\n";
    }
    
    if (segAttrs.revDirection != true) {
      newAttrs["revDirection"] = true;
      logmsg += "revDirection: " + segAttrs.revDirection + " => true";
    }
    
    wazeModel.actionManager.add(new Waze.Action.UpdateSegmentDetails(selsegments[i], newAttrs));
    consoleLog(logmsg);
    
    //wazeModel.actionManager.add(new Waze.Action.UpdateSegmentAddress(selsegments[i], {emptyStreet: false, name: 'Ferrovia'}));//emptyCity: true,
  }
  
  /* Abilito tutte le svolte sulle giunzioni */
  if (bOK) {
    console.log("S2WR: nodes: %o", nodes);
    /*for (var node in nodes) {
      wazeModel.actionManager.add(new Waze.Action.ModifyAllConnections(node, true));
    }*/
    /*Object.forEach(nodes, function(k, node) {
      wazeModel.actionManager.add(new Waze.Action.ModifyAllConnections(node, true));
    });*/
  }
}

function consoleLog(text) {
  console.log('S2WR: %s', text);
}

function s2wrMsg(text) {
  if (text.charAt(0) == '_') {
    if (s2wrLang != 'it') {
      alert(s2wrMessages.en[text]);
    } else {
      alert(s2wrMessages[s2wrLang][text]);
    }
  } else {
    alert(text);
  }
}

function initS2WR() {
  s2wrGlobals();
  s2wrWazeBits();
  console.log("S2WR: v. %s initialised", version);
  selectionManager.events.register("selectionchanged", null, s2wrInsertButton);
}

bootstrapS2WR();